package com.nowcoder.event;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.entity.DiscussPost;
import com.nowcoder.entity.Event;
import com.nowcoder.entity.Message;
import com.nowcoder.service.DiscussPostService;
import com.nowcoder.service.ElasticsearchService;
import com.nowcoder.service.MessageService;
import com.nowcoder.utils.CommunityConstant;
import com.nowcoder.utils.CommunityUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.quartz.Scheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Component
public class EventConsumer implements CommunityConstant {
    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    MessageService messageService;

    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    ElasticsearchService elasticsearchService;


    @KafkaListener(topics = {TOPIC_COMMENT, TOPIC_FOLLOW, TOPIC_LIKE})
    public void headerMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息类型为空");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null) return;

        // 发送站内通知，构造Message
        Message message = new Message();
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserid());
        message.setConversationId(event.getTopic());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());


        // 如果event data不为空，直接把全部放进去
        if(!event.getData().isEmpty()) {
            content.putAll(event.getData());
        }

        // 插入数据库
        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }

    @KafkaListener(topics = {TOPIC_PUBLISH})
    public void handlerPublicMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息类型为空");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null) return;

        // 存储帖子
        DiscussPost post = discussPostService.selectDiscussPostById(event.getEntityId());
        elasticsearchService.saveDiscussPost(post);
    }

    @Value("${wk.image.command}")
    String wkCmd;

    @Value("${wk.image.data}")
    String wkData;

    @Value("${qiniu.bucket.share}")
    String qiNiuBucketShare;

    @Value("${qiniu.sk}")
    String sk;

    @Value("${qiniu.ak}")
    String ak;

    @Autowired
    ThreadPoolTaskScheduler taskScheduler;

    @KafkaListener(topics = {TOPIC_SHARE})
    public void handlerShareMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息类型为空");
            return;
        }

        Event event = JSONObject.parseObject(record.value().toString(), Event.class);
        if(event == null) return;
        Map<String, Object> map = event.getData();
        String htmlUrl = (String) map.get("htmlUrl");
        String filename = (String) map.get("filename");
        String suffix = (String) map.get("suffix");
        String cmd = wkCmd + " --quality 75 " + htmlUrl + " " + wkData + "/" + filename + suffix;
        try {
            // 异步方法
            Runtime.getRuntime().exec(cmd);
            logger.info("生成长图成功: " + cmd);
        } catch (IOException e) {
            logger.error("生成长图失败: " + cmd + "\n" + e.getMessage());
            throw new RuntimeException(e);
        }

        // 启动定时器，监视图片
        UploadTask task = new UploadTask(filename, suffix);
        ScheduledFuture scheduledFuture = taskScheduler.scheduleAtFixedRate(task, 500);
        task.setScheduledFuture(scheduledFuture);
    }
    class UploadTask implements  Runnable{
        String fileName;
        String suffix;
        ScheduledFuture scheduledFuture;
        // 开始时间、结束时间
        Long startTime;
        int uploadTimes;

        public UploadTask(String fileName, String suffix) {
            this.fileName = fileName;
            this.suffix = suffix;
            this.startTime = System.currentTimeMillis();
        }

        public void setScheduledFuture(ScheduledFuture scheduledFuture) {
            this.scheduledFuture = scheduledFuture;
        }

        @Override
        public void run() {
            // 生成图片失败
            if(System.currentTimeMillis() - startTime > 30 * 10000) {
                logger.error("执行时间太长，终止任务" + fileName);
                scheduledFuture.cancel(true);
                return;
            }
            if(uploadTimes >= 3) {
                logger.error("上传次数过多，终止任务");
                scheduledFuture.cancel(true);
                return;
            }
            String path = wkData + "/" + fileName + suffix;
            File file = new File(path);
            if (file.exists()) {
                logger.info(String.format("开始第%d次上传[%s].", uploadTimes, fileName));
                uploadTimes++;
                // 设置响应信息
                StringMap policy = new StringMap();
                policy.put("returnBody", CommunityUtil.getJSONString(0));
                // 生成上传凭证
                Auth auth = Auth.create(ak, sk);
                String uploadToken = auth.uploadToken(qiNiuBucketShare, fileName, 3600, policy);
                // 指定上传机房
                UploadManager manager = new UploadManager(new Configuration(Region.huabei()));
                try {
                    // 开始上传图片
                    Response response = manager.put(path, fileName, uploadToken, null, "image/" + suffix, false);
                    // 处理响应结果
                    JSONObject json = JSONObject.parseObject(response.bodyString());
                    if (json == null || json.get("code") == null || !json.get("code").toString().equals("0")) {
                        logger.info(String.format("第%d次上传失败[%s].", uploadTimes, fileName));
                    } else {
                        logger.info(String.format("第%d次上传成功[%s].", uploadTimes, fileName));
                        scheduledFuture.cancel(true);
                    }
                } catch (QiniuException e) {
                    logger.info(String.format("第%d次上传失败[%s].", uploadTimes, fileName));
                }
            }else {
                logger.info("等待图片生成[" + fileName + "].");
            }
        }
    }
}










